package cs633.util;

import java.sql.*;
import java.util.ResourceBundle;

public class DBManager {
	private static DBManager _instance = null;
	Connection conn = null;
	ResourceBundle rb = null;
	
	private DBManager() {
		init();
	}
	public static DBManager getInstance() {
		if (_instance == null) {
			_instance = new DBManager();
		}
		return _instance;
	}
	private void init() {
		try {
			Class.forName("com.mysql.jdbc.Driver").newInstance();
			rb = ResourceBundle.getBundle("resource");
		} catch (Exception e) {
			System.out.println("Error: " + e.getMessage());
		}
	}
	
	public Connection getConn() {
		try {
			String str = rb.getString("driver");
			if (str != null) 
				conn = DriverManager.getConnection(str);
			
		} catch (SQLException sqle) {
			System.out.println("Error: " + sqle.getMessage());
		}
		return conn;
	}
	public void dropConn(Connection conn) {
		try {
			conn.close();
		} catch (SQLException sqle) {
			System.out.println("Error: " + sqle.getMessage());
		}
	}
	
	public static boolean testConn() {
		boolean result = true;
		Connection conn = null;
		try {
			conn = getInstance().getConn();
			String sql = "SELECT * FROM cs633.user";			
			PreparedStatement pstmt = conn.prepareStatement(sql);
			ResultSet rs = pstmt.executeQuery();
			while (rs.next()) {
				System.out.println(rs.getString("USER_SEQ_ID"));
				System.out.println(rs.getString("USER_ID"));
				System.out.println(rs.getString("USER_FIRST_NAME"));
				System.out.println(rs.getString("USER_LAST_NAME"));
			}
				
			 conn.close();
			 System.out.println("Database connection okay!");
		} catch (Exception error) {
			System.out.println("Error getting database connection: " + error.toString());
			result = false;
		}
		return result;
	}
}
